package com.yeban.javase.day12;

import com.yeban.javase.day01.Person;

import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/21
 *
 * 练习2.定义一个Person数组，将Person数组中的重复对象剔除
 */
public class HashSetTest2 {

    public static void main(String[] args) {
        Person2[] persons = new Person2[5];
        persons[0] = new Person2("张三", 18);
        persons[1] = new Person2("李四", 19);
        persons[2] = new Person2("王五", 20);
        persons[3] = new Person2("张三", 18);

        // Arrays.aslist将数组转换成集合
        Set<Person2> set = new HashSet<>(Arrays.asList(persons));
        /*for (Person2 p : persons) {
            if (p != null) {
                set.add(p);
            }
        }*/
        // System.out.println(set);
        // toArray
        Person2[] persons2 = set.toArray(new Person2[set.size()]);
        System.out.println(Arrays.toString(persons2));
    }
}

class Person2 {
    private String name;
    private int age;


    public Person2() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person2 person2 = (Person2) o;
        return age == person2.age && Objects.equals(name, person2.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public Person2(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Person2{name = " + name + ", age = " + age + "}";
    }
}
